#include "lockfree_stack.h"
#include <stdlib.h>
#include "../atomic/cpu_pause.h"

void stack_init(stack_t* stack) {
    atomic_store(&stack->top, NULL, memory_order_relaxed);
}

bool stack_push(stack_t* stack, void* data) {
    node_t* new_node = malloc(sizeof(node_t));
    if (!new_node) return false;
    
    new_node->data = data;
    
    do {
        node_t* old_top = atomic_load(&stack->top, memory_order_acquire);
        new_node->next = old_top;
        
        if (atomic_compare_exchange_weak(&stack->top, &old_top, new_node,
                                      memory_order_release,
                                      memory_order_relaxed)) {
            return true;
        }
        cpu_pause(); // 添加暂停以减少竞争
    } while (1);
}

void* stack_pop(stack_t* stack) {
    do {
        node_t* old_top = atomic_load(&stack->top, memory_order_acquire);
        if (old_top == NULL) {
            return NULL;  // 栈为空
        }
        
        node_t* new_top = old_top->next;
        if (atomic_compare_exchange_weak(&stack->top, &old_top, new_top,
                                      memory_order_release,
                                      memory_order_relaxed)) {
            void* data = old_top->data;
            free(old_top);
            return data;
        }
        cpu_pause(); // 添加暂停以减少竞争
    } while (1);
}

bool stack_is_empty(stack_t* stack) {
    return atomic_load(&stack->top, memory_order_acquire) == NULL;
} 